/**
 *  
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from '@router'
import store from '@store'
import settings from '@config/index'
import getPageTitle from '@utils/pageTitle'

const lastRoute = {
  path: '/:pathMatch(.*)*',
  component: () => import('@/views/error/404.vue'),
  meta: {
    title: '找不到页面'
  }
}

router.beforeEach(async(to, from, next) => {
  // 判断是否有token（有继续，无跳转登录界面）
  let hasToken
  // 判断是否需要toekn 认证
  if (!settings.isNeedTokenInfo) {
    hasToken = true
  } else {
    hasToken = store.getters['user/accessToken']
  }
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 是否有权限
      const hasRoles =
        store.getters['user/admin'] ||
        store.getters['user/role'].length > 0 ||
        store.getters['user/authorities'].length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          if (settings.isNeedTokenInfo) {
            await store.dispatch('user/getLoginUserInfo')
          } else {
            // 创建虚拟角色
            await store.dispatch('user/setVirtualRoles')
          }

          let accessRoutes = []
          if (settings.generationRouteBy === 'frontEndGeneration') {
            accessRoutes = await store.dispatch('routes/setRoutes')
          } else if (settings.generationRouteBy === 'backendGeneration') {
            accessRoutes = await store.dispatch('routes/setAllRoutes')
            accessRoutes.push(lastRoute)
          }
          accessRoutes.forEach(item => {
            router.addRoute(item)
          })
          next({ ...to, replace: true })
        } catch (err) {
          console.error(err)
          await store.dispatch('user/resetAll')
          if (settings.recordRoute)
            next({
              path: '/login',
              query: { redirect: to.path },
              replace: true
            })
          else next({ path: '/login', replace: true })
        }
      }
    }
  } else {
    if (settings.routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (settings.recordRoute)
        next({ path: '/login', query: { redirect: to.path }, replace: true })
      else next({ path: '/login', replace: true })
    }
  }
})
router.afterEach(to => {
  document.title = getPageTitle(to.meta.title)
})
